package algorithms;

public class 二叉树遍历 {
    public static void main(String[] args) {
        Node n1 = new Node(6);

        Node n2 = new Node(5);

        Node n3 = new Node(7);

        Node n4 = new Node(2);

        Node n5 = new Node(5);

        Node n6 = new Node(8);

        n1.left = n2;
        n1.right = n3;

        n2.left = n4;
        n2.right = n5;

        n3.right = n6;

        firstTraverse(n1);
        System.out.println("------------------------");
        midTraverse(n1);
        System.out.println("------------------------");
        afterTraverse(n1);
    }

    private static class Node {
        Node left;
        Node right;
        int v;

        public Node(int v) {
            this.v = v;
        }
    }


    /**
     * 先序遍历
     *
     * @param node
     */
    private static void firstTraverse(Node node) {
        if(node == null){
            return;
        }

        System.out.println(node.v);

        Node left = node.left;
        Node right = node.right;

        firstTraverse(left);
        firstTraverse(right);
    }

    /**
     * 中序遍历
     *
     * @param node
     */
    private static void midTraverse(Node node) {
        if(node == null){
            return;
        }



        Node left = node.left;
        midTraverse(left);

        System.out.println(node.v);

        Node right = node.right;
        midTraverse(right);
    }

    /**
     * 后序遍历
     *
     * @param node
     */
    private static void afterTraverse(Node node) {
        if(node == null){
            return;
        }

        Node left = node.left;
        Node right = node.right;
        afterTraverse(left);
        afterTraverse(right);

        System.out.println(node.v);
    }
}
